//index.js
const app = getApp()

Page({
  data: {
    datasource: []
  },
  onLoad() {
    this.bindconfirm()
  },
  tap(e) {


    const item = e.currentTarget.dataset.item
    var link = item.link
    var history = wx.getStorageSync('history')
    var datasource = []
    if (history) {
      datasource = JSON.parse(history)
    }
    var itemStr = JSON.stringify(item)
    var count = datasource.indexOf(itemStr)
    if (count != -1) {
      datasource.splice(count, 1)
    }
    datasource.splice(0, 0, itemStr)

    wx.setStorageSync('history', JSON.stringify(datasource))

    wx.navigateTo({
      url: '../section/section?link=' + item.link,
    })
  },
  bindconfirm(e) {

    wx.showLoading({
      title: '加载中',
    })

    var key = e ? e.detail.value : 'p'
    if (key.length === 0) {
      key = 'p'
    }
    const that = this
    wx.request({
      url: 'https://m.bixiadu.com/SearchBook.aspx?keyword=' + key + '&t=1',

      method: 'POST',
      // responseType:'arraybuffer',
      // header:{
      //   'content-type':'application/x-www-form-urlencoded'
      // },
      success: ((res) => {
        // console.log('data')
        // console.log(res)
        var datasource = []
        const alllist = res.data.split('<div class="recommend mybook">')
        for (var key in alllist) {
          var arr = alllist[key].split('<a href="')

          for (var keya in arr) {
            var item = arr[keya]

            var titleArray = item.split('<p class="author">')

            if (titleArray.length === 1) {
              continue
            }

            // console.log(titleArray)

            var link = titleArray[0].split('<p class="title">')[0].split('">')[0]
            // console.log(title)

            var title = titleArray[0].split('<p class="title">')[1].split('</p>')[0]
            // console.log(link)

            var writer = titleArray[1].split('</p>')[0]

            var section = titleArray[2].split('</p>')[0]
            var data = {
              title: title,
              link: link,
              section: section,
              writer: writer
            }
            datasource.push(data)

          }

        }
        that.setData({
          datasource: datasource
        })
        wx.hideLoading()
        // wx.navigateTo({
        //   url: '../webview/webview',
        // })
      }),
      fail: ((e) => {
        console.log(e)
      })
    })
  }
})